﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using global::TerhelesEloszto.Common;
using global::TerhelesEloszto.Engine;

namespace Presentation
{
	public partial class AddInterval : System.Web.UI.Page
	{
		IEngine engine = global::TerhelesEloszto.Engine.Engine.Instance();
		protected void Page_Load( object sender, EventArgs e )
		{
			String visitorName = User.Identity.Name;
			if( !engine.IsAdmin( visitorName ) )
			{
				if( engine.IsTeacher( visitorName ) )
				{
					Response.Redirect( "~/Teacher/TeacherProblem.aspx" );
				}
				else
				{
					Response.Redirect( "~/Problem.aspx" );
				}

			}

		}

		protected void CreateButton_Click( object sender, EventArgs e )
		{
			if( Convert.ToInt32( BeginList.SelectedValue ) >= Convert.ToInt32( EndList.SelectedValue ) )
			{
				Response.Redirect( "~/Admin/Task.aspx?msg=0" );
			}


			DayOfWeek day = DayOfWeek.Sunday;
			switch( DayList.SelectedValue )
			{
				case "Hétfő": day = DayOfWeek.Monday; break;
				case "Kedd": day = DayOfWeek.Tuesday; break;
				case "Szerda": day = DayOfWeek.Wednesday; break;
				case "Csütörtök": day = DayOfWeek.Thursday; break;
				case "Péntek": day = DayOfWeek.Friday; break;
				case "Szombat": day = DayOfWeek.Saturday; break;
				case "Vasárnap": day = DayOfWeek.Sunday; break;
			}
			bool parity = true;
			switch( WeekList.SelectedValue )
			{
				case "Páros": parity = false; break;
				case "Páratlan": parity = true; break;
			}
			IInterval newInterval = engine.ConstructInterval( day, Convert.ToInt32( BeginList.SelectedValue ), Convert.ToInt32( EndList.SelectedValue ), parity );

			ITask taskToModify = null;
			foreach( ITask actTask in engine.GetTasks() )
			{
				if( actTask.ID.ToString().Equals( Request.QueryString["ID"] ) )
				{
					taskToModify = actTask;
					break;
				}
			}

			foreach( IInterval iv in taskToModify.TimeIntervals )
			{
				if( iv.HasIntersect( newInterval ) )
				{
					Response.Redirect( "~/Admin/Task.aspx?msg=0" );
				}
			}

			try
			{
				taskToModify.TimeIntervals.Add( newInterval );
				engine.UpdateTask( taskToModify, taskToModify.RelatedFact, taskToModify.Name, taskToModify.Type, taskToModify.RequiredSkills, taskToModify.TimeIntervals, taskToModify.Semester );

			}
			catch( EngineException ex )
			{
				Response.Redirect( "~/Admin/Task.aspx?msg=0" );
			}
			Response.Redirect( "~/Admin/Task.aspx?msg=1" );
		}
	}
}